package com.nmgs.util.zip;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public class TarGzUtil {
    private static final Logger logger = LoggerFactory.getLogger(TarGzUtil.class);
    /**
     * 解压tar.gz格式的压缩包为tar压缩包
     * @param sourcePath 待解压文件路径
     * @param destPath 解压路径
     */
    public static void unCompressTarGz(String sourcePath, String destPath) throws IOException {
        long start = System.currentTimeMillis();
        File sourceFile = new File(sourcePath);
        logger.info("start to unpack tar.gz file, file name:{}", sourceFile.getName());
        unCompressTarGz(sourceFile, destPath);
        logger.info("finish unpack tar.gz file, file name:{}, cost:{} ms", sourceFile.getName(), System.currentTimeMillis() - start);
    }


    /**
     * 解压tar.gz格式的压缩包为tar压缩包
     * @param sourceFile 待解压文件
     * @param destPath 解压路径
     */
    public static void unCompressTarGz(File sourceFile, String destPath) throws IOException {
        long start = System.currentTimeMillis();
        logger.info("start to unpack tar.gz file, file name:{}", sourceFile.getName());
        unCompressTarGz(new FileInputStream(sourceFile), destPath);
        logger.info("finish unpack tar.gz file, file name:{}, cost:{} ms", sourceFile.getName(), System.currentTimeMillis() - start);
    }


    /**
     * 解压tar.gz格式的压缩包为tar压缩包
     * @param inputStream 待解压文件输入流
     * @param destPath 解压路径
     */
    public static void unCompressTarGz(InputStream inputStream, String destPath) throws IOException {
        logger.info("start to unpack tar.gz fileInputStream");
        try (FileInputStream fileInputStream = (FileInputStream) inputStream;
             GzipCompressorInputStream gzipCompressorInputStream = new GzipCompressorInputStream(fileInputStream);
             TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(gzipCompressorInputStream, "UTF-8")) {
            TarArchiveEntry entry;
            while ((entry = tarArchiveInputStream.getNextTarEntry()) != null) {
                if (entry.isDirectory()) {
                    continue;
                }
                File curFile = UtilFile.newFileWithCheck(destPath, entry.getName());
                File parent = curFile.getParentFile();
                if (!parent.exists()) {
                    parent.mkdirs();
                }
                try (FileOutputStream outputStream = new FileOutputStream(curFile)) {
                    IOUtils.copy(tarArchiveInputStream, outputStream);
                }
            }
        }
        logger.info("finish unpack tar.gz file");
    }

}

